package com.yunhe.marketing.handler;

import com.yunhe.common.util.RedisClient;
import com.yunhe.marketing.domain.CompanyHeat;
import com.yunhe.marketing.service.ICompanyHeatService;
import com.yunhe.common.util.CollectionUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhengbo
 * @date 2021/3/16 15:50
 * 启动时初始化redis中的企业热度值
 */

@Order(value = 1)
@Component
public class InitializeCompanyHeatHandle implements ApplicationRunner {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ICompanyHeatService iCompanyHeatService;

    private Logger logger = Logger.getLogger(InitializeCompanyHeatHandle.class);

    /**redis key的部分前缀*/
    private static final String HEAT_COMPANY = "heat:company:";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("MarketingServerApplication start success then run InitializeCompanyHeatHandle.........");
        List<CompanyHeat> companyHeatList = iCompanyHeatService.selectAllHeatCompanyList();
        if (CollectionUtil.isNotEmpty(companyHeatList)) {
            companyHeatList.forEach(companyHeat -> {
                if (redisClient.exists(HEAT_COMPANY + companyHeat.getItemId())) {
                    String companyHeatValue = redisClient.get(HEAT_COMPANY + companyHeat.getItemId());
                    //value的格式为value: 2;2;0.834031
                    if (companyHeatValue.equals(companyHeat.getHeat())) {
                        logger.info("key: " + HEAT_COMPANY + companyHeat.getItemId() + " is exist, no need to operate");
                    }
                } else {
                    redisClient.set(HEAT_COMPANY + companyHeat.getItemId(), companyHeat.getHeat());
                    logger.info("key: " + HEAT_COMPANY + companyHeat.getItemId() + " write successfully");
                }
            });
        }
    }
}
